package com.inspur.sc.springboot.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspur.sc.springboot.entity.SysRole;
import com.inspur.sc.springboot.service.SysRoleService;
import com.inspur.sc.springboot.utils.ResponseUtil;
import com.inspur.sc.springboot.vo.DataTablesVO;
import com.inspur.sc.springboot.vo.QueryVO;
import com.inspur.sc.springboot.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/role")
public class SysRoleController {

    @Autowired
    private SysRoleService roleService;

    @PostMapping("findRoleByLike")
    public DataTablesVO<SysRole> findRoleByLike(QueryVO queryVO){
        Integer pageNo=queryVO.getStart()/queryVO.getLength();
        Pageable pageable= PageRequest.of(pageNo,queryVO.getLength());
        Page<SysRole> page= roleService.findByNameLike("%"+queryVO.getSearch()+"%",pageable);
        DataTablesVO<SysRole> result=new DataTablesVO<>(page.getContent(),page.getTotalElements(),page.getTotalElements(),queryVO.getDraw());
        return result;
    }

    @GetMapping("findAllRole")
    public ResponseEntity<ResponseVO> findAllRole(){
        List<SysRole> roles= roleService.findAll();
        JSONArray result=new JSONArray();
        roles.forEach(role->{
            JSONObject object=new JSONObject();
            object.put("value",role.getId());
            object.put("text",role.getDescription());
            result.add(object);
        });
        return ResponseUtil.success(result);
    }

    @PostMapping("save")
    public ResponseEntity<ResponseVO> save(@RequestBody SysRole sysRole){

        boolean isSave=roleService.save(sysRole);
        if(isSave ){
            return ResponseUtil.success("保存成功",true);
        }
        return ResponseUtil.success("保存失败",false);
    }

    @PostMapping("getRole")
    public ResponseEntity<ResponseVO> getRole(@RequestParam(value = "id") Integer id){
        SysRole sysRole=roleService.findSysRoleById(id);
        if(null != sysRole){
            return ResponseUtil.success(sysRole);
        }
        return ResponseUtil.success(null);
    }

    @PostMapping("delete")
    public ResponseEntity<ResponseVO> delete(@RequestParam(value = "id") Integer id){
        boolean isDel=roleService.deleteById(id);
        if(isDel){
            return ResponseUtil.success("删除成功!");
        }
        return ResponseUtil.success("删除失败!");
    }
}
